#!/bin/bash
# Put this file into /usr/local/bin then you can run pikvm-info anywhere while logged in to Pi-KVM terminal/ssh
#
uptime
NAME=$( egrep ^NAME= /etc/os-release | cut -d'"' -f2 )
echo "Host OS:  $NAME `uname -r`  `uname -m`"

# pistat is built-in to pi-kvm (/usr/local/bin)
pistat && echo

printf "%-32s\t%s\n" "Version" "Package-Name" "---------------------------------" "-----------------------------"

get-packages() {
if [[ $( echo $NAME | cut -d' ' -f1 ) == "Arch" ]]; then
        if [ ! -e $TMPFILE ]; then
                pacman -Q | awk '{print $2, $1}' > $TMPFILE
        fi

else
        KVMDPLAT=$( grep kvmd-platform /var/cache/kvmd/installed_ver.txt | awk '{print $4}' | awk -F\/ '{print $NF}' | tail -1 )
        if [[ "$KVMDPLAT" != "" ]]; then
                KVMDVER=$( echo $KVMDPLAT | cut -d'-' -f6 )
                PLATFORM=$( echo $KVMDPLAT | cut -d'-' -f1,2,3,4,5 )
                printf "%-32s\t%s\n" $KVMDVER $PLATFORM
        fi

        USTREAMVER=$( /usr/bin/ustreamer -v )
        printf "%-32s\t%s\n" $USTREAMVER "ustreamer"
        #JANUSVER=$( /usr/bin/janus -V | tail -1 | awk '{print $NF}' )
        JANUSVER=$( /usr/bin/janus -V | egrep 'version|janus' | awk '{print $NF}' | sed -e 's|(||g' -e 's|)||g' )
        printf "%-32s\t%s\n" $JANUSVER "janus"
        TTYDVER=$( ttyd -v | awk '{print $NF}' )
        printf "%-32s\t%s\n" $TTYDVER "ttyd"

        if [ ! -e $TMPFILE ]; then
                apt list 2> /dev/null | egrep 'upgradable|installed' | grep -v ^$ | awk '{print $2, $1}' > $TMPFILE
        fi

fi
} # end get-packages


TMPFILE="/tmp/pacmanquery"

get-packages
PACKAGES="janus pikvm kvmd ustreamer nginx wpa wireless python3/stable python$ firmware raspberrypi tailscale"
for PKG in $( echo $PACKAGES ); do
        if [ $(grep -w $PKG $TMPFILE | wc -l) -gt 0 ]; then
                printf "%-32s\t%s\n" $(grep -w $PKG $TMPFILE | sed 's/-[1-9]+//g' | awk -F\/ '{print $1}' )
        fi
done | sort -u | sort -k2
